<?php


namespace app\model;

use think\facade\Cache;
use think\facade\Db;
use think\response\Json;
use \Exception as E;

class DormitoryModel
{
    private static $_table = 'eb_dormitory'; // 宿舍表
    private static $_schoolTable = 'eb_school'; // 学校表
    private static $_floorTable = 'eb_floor'; // 楼层表
    private static $_schoolRoleTable = 'eb_school_role'; // 学校角色管理

    /**添加
     * @param $input
     * @param $token
     * @return Json
     */
    public static function increase($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            $map = [
                ['id', '=', $input['school_id']],
                ['operate_id', '=', $admin['id']]
            ];
            $sql1 = Db::table(self::$_schoolTable)->field('id')->where($map)->fetchSql(true)->find();
            $map = [
                ['id', '=', $input['manag_id']],
                ['operate_id', '=', $admin['id']],
                ['type', '=', 3]
            ];
            $sql2 = Db::table(self::$_schoolRoleTable)->field('id')->where($map)->fetchSql(true)->find();
            $where = "exists ({$sql1}) and exists ({$sql2})";
            $input['create_time'] = time();
            $input['operate_id'] = $admin['id'];
            $sql = makeDualSql(self::$_table, $input, $where);
            Db::startTrans();
            $flag = true;
            $rtn = Db::table(self::$_table)->execute($sql);
            if ($rtn) {
                //添加缓存
                $map = [
                    ['name', '=', $input['name']]
                ];
                $dorId = Db::table(self::$_table)->field('id')->where($map)->find();
                if (!$dorId) {
                    Db::rollback();
                    return jsonFail('添加失败！');
                }
                $addRtn = Cache::store('redis')->handler()->hSet('dxsd-school-' . $input['school_id'], 'dormitory-' . $dorId['id'], json_encode(['manag_id' => $input['manag_id']]));
                if ($addRtn === 1) {
                    Db::commit();
                    return jsonSuccess('添加成功！');
                } else {
                    Db::rollback();
                    return jsonFail('添加失败！');
                }
            } else {
                Db::rollback();
                return jsonFail('该学校名已使用，添加失败！');
            }
        } catch (E $e) {
            if ($flag == true) Db::rollback();
            if ($e->getMessage() === "SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '{$input['name']}' for key 'name'") {
                return jsonFail('该名字已被使用');
            }
            return jsonFail('服务内部错误~');
        }
    }

    /**列表
     * @param $input
     * @param $token
     * @return Json
     */
    public static function list($input, $token)
    {
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            $map[] = ['d.operate_id', '=', $admin['id']];
            $map[] = ['d.school_id', '=', $input['school_id']];
            if ($input['gender'] !=='') $map[] = ['d.gender', '=', $input['gender']];
            if ($input['name'] !== '') $map[] = ['d.name', 'like', "%{$input['name']}%"];
            $table = Db::table(self::$_table)->alias('d')
                ->leftJoin([self::$_schoolRoleTable => 'sr'], 'sr.id = d.manag_id')
                ->field('d.id,d.name,d.gender,sr.name as manager_name,FROM_UNIXTIME(d.create_time, "%Y-%m-%d %H:%i:%s") AS create_time')
                ->where($map);
            $count = $table->count();
            if ($count == 0) return jsonSuccess('查询成功', ['count' => 0, 'list' => []]);
            $list = $table->order('d.create_time', 'desc')->page($input['page'], $input['limit'])->select()->toArray();
            return jsonSuccess('查询成功', ['count' => $count, 'list' => $list]);
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**删除
     * @param $input
     * @param $token
     * @return Json
     */
    public static function delete($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            $map = [
                ['dormitory_id', '=', $input['id']],
                ['operate_id', '=', $admin['id']],
                ['school_id', '=', $input['school_id']]
            ];
            $sql = Db::table(self::$_floorTable)->field('id')->where($map)->fetchSql(true)->find();
            $map = [
                ['id', '=', $input['id']],
                ['operate_id', '=', $admin['id']],
                ['school_id', '=', $input['school_id']]
            ];
            Db::startTrans();
            $flag = true;
            $rtn = Db::table(self::$_table)->where($map)->whereNotExists($sql)->delete();
            if ($rtn) {
                // 删除缓存
                $delRtn = Cache::store('redis')->handler()->hDel('dxsd-school-' . $input['school_id'], 'dormitory-' . $input['id']);
                if ($delRtn === 1) {
                    Db::commit();
                    return jsonSuccess('删除成功！');
                } else {
                    Db::rollback();
                    return jsonFail('删除失败！');
                }
            } else {
                Db::rollback();
                return jsonFail('未找到数据或者存在未删除的楼层，请先刷新确认');
            }
        } catch (E $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**获取单个
     * @param $input
     * @param $token
     * @return Json
     */
    public static function getOnly($input, $token)
    {
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            $managerInfo = SchoolRoleModel::getRoleTypeListStatic($input['school_id'], $admin['id'], 3);
            if (!is_array($managerInfo)) return $managerInfo;
            $map = [
                ['id', '=', $input['id']],
                ['operate_id', '=', $admin['id']],
                ['school_id', '=', $input['school_id']]
            ];
            $rtn = Db::table(self::$_table)->field('id, name,gender,manag_id,school_id')->where($map)->find();
            if ($rtn) return jsonSuccess('获取成功', ['managerInfo' => $managerInfo, 'info' => $rtn]);
            return jsonFail('获取失败');
        } catch (E $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**编辑
     * @param $input
     * @param $token
     * @return Json
     */
    public static function edit($input, $token)
    {
        $flag = false;
        try {
            // 检测当前管理员状态
            $admin = AdminModel::getInfo($token, [1], [2]);
            if ($admin instanceof Json) return $admin;
            $map = [
                ['id', '=', $input['id']],
                ['operate_id', '=', $admin['id']],
                ['school_id', '=', $input['school_id']]
            ];
            $id = $input['id'];
            unset($input['id']);
            $schoolId = $input['school_id'];
            unset($input['school_id']);
            Db::startTrans();
            $flag = true;
            $rtn = Db::table(self::$_table)->where($map)->update($input);
            if ($rtn) {
                // 更新缓存
                $dorInfo = Cache::store('redis')->handler()->hGet('dxsd-school-' . $schoolId, 'dormitory-' . $id);
                if (!$dorInfo) {
                    Db::rollback();
                    return jsonFail('编辑失败！');
                }
                $dorInfo = json_decode($dorInfo, true);
                $dorInfo['manag_id'] = $input['manag_id'];
                $editRtn = Cache::store('redis')->handler()->hSet('dxsd-school-' . $schoolId, 'dormitory-' . $id, json_encode($dorInfo));
                if ($editRtn === 0) {
                    Db::commit();
                    return jsonSuccess('编辑成功！');
                } else {
                    Db::rollback();
                    return jsonFail('编辑失败！');
                }
            } else {
                Db::rollback();
                return jsonFail('数据未更改编辑失败');
            }
        } catch (E $e) {
            if ($flag == true) Db::rollback();
            if ($e->getMessage() === "SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '{$input['name']}' for key 'name'") {
                return jsonFail('该名字已被使用');
            }
            return jsonFail('服务内部错误~');
        }
    }
}